package com.meixiang.activity.moments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.homes.service.ShowPictureActivity;
import com.meixiang.adapter.moments.PostDetailsAdapter;
import com.meixiang.dialog.GrildDialogFragment;
import com.meixiang.entity.account.ShardLike;
import com.meixiang.entity.moments.PostDetailsBean;
import com.meixiang.entity.moments.PostDetailsItemBean;
import com.meixiang.entity.moments.PostDetailsList;
import com.meixiang.global.Config;
import com.meixiang.global.ContentHint;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.shardApi.ShareContentCustomize;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.system.text.ShortMessage;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import okhttp3.Call;
import okhttp3.Response;

//import cn.sharesdk.framework.Platform;

/**
 * 作者：黑哥 on 2016/5/6 19:05
 * 帖子详情
 * 回复子布局  list_item_reply
 */
public class PostDetailsActivity extends BaseActivity implements OnRefreshListener {
    private static final String TAG = "PostDetailsActivity";

    @Bind(R.id.tv_comment_number)
    TextView mTvCommentNumber;
    @Bind(R.id.tv_back)
    ImageView mTvBack;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.iv_comment)
    ImageView mIvComment;
    @Bind(R.id.iv_praise)
    ImageView mIvPraise;
    @Bind(R.id.iv_share)
    ImageView mIvShare;
    @Bind(R.id.ll_input_dialog_box)
    LinearLayout mLlInputDialogBox;
    @Bind(R.id.tv_praise_number)
    TextView mTvPraiseNumber;
    @Bind(R.id.et_input_dialog_box)
    ClearEditText mEdInputDialogBox;
    @Bind(R.id.tv_send_message)
    TextView mTvSendMessage;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;

    private int pageNo = 1, pageSize = 3, totalPage = 0;
    private Activity mActivity;
    @Bind(R.id.swipe_target)
    RecyclerView mRecyclerView;
    private PostDetailsAdapter mAdapter;
    private PostDetailsBean mBean;

    private PostDetailsList mList;

    private List<PostDetailsItemBean> mItemList;
    private boolean isLikeClick = false;
    private boolean isRefresh = true;
    private String CommentId;
    private String MemberId;
    private String content;
    private String[] UrlPath;
    private String imagPath,linkUrl;

    private ShardLike mShardLike;
    // sdcard中的图片名称

    private static final String FILE_NAME = "/share_pic.jpg";
    public static String TEST_IMAGE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_post_details);
        ShareSDK.initSDK(this);
        ButterKnife.bind(this);
        mActivity = PostDetailsActivity.this;
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initTitle() {
        mTvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initImagePath();
        mIvShare.setOnClickListener(this);
    }

    @Override
    protected void initView() {
        if (getIntent().getExtras().getString("commentId") != null) {
            CommentId = getIntent().getExtras().getString("commentId");
        }
        mRefresh.setOnRefreshListener(this);
        mRefresh.setLoadMoreEnabled(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new PostDetailsAdapter(mActivity, mActivity);
        mRecyclerView.setAdapter(mAdapter);
        mTvSendMessage.setOnClickListener(this);

        mAdapter.setOnItemClickListener(new PostDetailsAdapter.onItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {

                Log.e("TAG","查看详情position="+position);
                MemberId = mAdapter.getListData().get(position).getMemberId();
                autoPopupKeyboard();
            }

            @Override
            public void onAttentionItemClick(View v, int position) {
                //未关注

            }
            //相册点击事件

            @Override
            @SuppressWarnings("unchecked")
            public void onPhotoonItemClick(View v, int position) {
                if (Tool.isFastDoubleClick()) return;
                Intent intent = new Intent(activity, ShowPictureActivity.class);
                ArrayList<String> list = new ArrayList(Arrays.asList(mAdapter.getData().getCommentImages()));
                content = mAdapter.getData().getComment();
                UrlPath = mAdapter.getData().getCommentImages();
                Log.e("TAG", "输出当前的UrlPath=" + UrlPath);
                intent.putStringArrayListExtra("urls", list);
                intent.putExtra("position", position);
                startActivity(intent);
            }
        });

        mIvComment.setOnClickListener(this);
        mIvPraise.setOnClickListener(this);
        mLlInputDialogBox.setOnClickListener(this);

    }

    @Override
    protected void setData() {

        if (getIntent().getExtras().getString("comment") != null) {
            if (getIntent().getExtras().getString("comment").equals("1")) {
                //autoPopupKeyboard();
            }

        }
        status.showLoading();
        getDetailedData(1, true);
        //获取分享内容

        getShardData();

    }

    private void getShardData() {
        HttpParams params = new HttpParams();
        params.put("commentId", CommentId);
        HttpUtils.post(Config.SHARD_LIKE, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Log.e("TAG","得到数据="+result.toString());

                mShardLike = new Gson().fromJson(result.toString(), ShardLike.class);

                if(mShardLike.getCommentImages()!=null&&mShardLike.getCommentImages().length>0){
                        imagPath = mShardLike.getCommentImages()[0];
                        Log.e("TAG","输出第一张图片=="+imagPath);
                }else{
                    imagPath ="";
//                    Log.e("TAG","输出数据imagPath=="+imagPath);


                }
                if(mShardLike.getComment()!=null){
                    content=mShardLike.getComment();
                }else {
                    content="";
                }if(mShardLike.getUrl()!=null){
                    linkUrl=mShardLike.getUrl();
                }


//                imagPath=result.optString("commentImages");
//                content=result.optString("");


            }

            @Override
            public void onError(String code, String message) {

            }
        });


    }

    public void getDetailedData(int pageNo, final boolean isPull) {
        HttpParams params = new HttpParams();
        params.put("pageSize", pageSize + "");
        params.put("pageNo", pageNo + "");
        params.put("commentId", CommentId);
        HttpUtils.post(Config.MOMENTS_POST_DETAILS, params, new HttpCallBack(mActivity) {

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                String json = null;
                try {
                    if (isPull) {
                        mAdapter.clear();
                    }

                    mList = new Gson().fromJson(result.toString(), PostDetailsList.class);
                    json = result.getString("commentList");
                    mItemList = new Gson().fromJson(json, new TypeToken<List<PostDetailsItemBean>>() {
                    }.getType());

                    if (mList == null) {
                        status.showNoData(ContentHint.NO_DATA);
                    } else {
                        status.removeView();
                        mAdapter.addAll(mItemList);
                        mAdapter.addData(mList);
                        mTvCommentNumber.setText(mList.getCommentNumber());
                        mTvPraiseNumber.setText(mList.getLaudNumber());
                        if (mList.getMyLaud().equals("1")) {
                            isLikeClick = true;
                            mIvPraise.setImageResource(R.mipmap.praise_like);
                        } else {
                            isLikeClick = false;
                            mIvPraise.setImageResource(R.mipmap.praise_like_up);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String code, String message) {
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getDetailedData(1, true);
                    }
                });

                AbToastUtil.showToast(context, message);
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (mRefresh.isRefreshing()) {
                    mRefresh.setRefreshing(false);
                }
            }
        });


    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_share:

                new GrildDialogFragment(context, new GrildDialogFragment.IResultListener() {
                    @Override
                    public void SelectResult(int position) {
                        if(position == 0) {
                            showShare(true, SinaWeibo.NAME);
                        }
                        if(position == 1){
                            showShare(true, QQ.NAME);
                        }
                        if(position == 2){
                            showShare(true, QZone.NAME);
                        }
                        if(position == 3){
                            showShare(true, Wechat.NAME);
                        }
                        if(position == 4){
                            showShare(true, WechatMoments.NAME);
                        }
                        if(position == 5){
                            showShare(true, ShortMessage.NAME);
                        }if(position == 6){
                            if (Tool.isFastDoubleClick()) return;
                            Intent intent =new Intent(mActivity,AccusationActivity.class);
                            intent.putExtra("CommentId",CommentId);
                            startActivity(intent);
                            finish();
                        }

                    }
                });
                break;
            case R.id.ll_input_dialog_box:
                autoPopupKeyboard();
                break;
            case R.id.iv_comment:
                autoPopupKeyboard();
                break;
            case R.id.et_input_dialog_box:
                autoPopupKeyboard();
                break;
            case R.id.tv_send_message:
                if (MXApplication.mApp.getUser().getMemberId().equals(MemberId)) {
                    Tool.showTextToast(mActivity, "这是您自己的评论哟");
                    return;
                }
                if (Tool.isBlank(mEdInputDialogBox.getText().toString())) {
                    Tool.showTextToast(mActivity, "请输入评论消息");
                    return;
                }
                doSendMessage();
                break;
            case R.id.iv_praise:
                doLikeRraise();
                break;
        }
    }

    private void doLikeRraise() {
        if (isLikeClick == false) {
            HttpParams params = new HttpParams();
            params.put("commentId", CommentId);
            HttpUtils.post(Config.MOMENTS_ADD_LAUD, params, new HttpCallBack(mActivity) {
                @Override
                public void onSucceed(JSONObject result, String code, String message) {
                    Tool.showTextToast(context, message);
                    mTvPraiseNumber.setText(result.optString("laudNumber"));
                    mTvPraiseNumber.setTextColor(ContextCompat.getColor(context, R.color.magenta));
                    mIvPraise.setImageResource(R.mipmap.praise_like);
                    Tool.Like(mActivity, mTvPraiseNumber);
                    isLikeClick = true;
                }

                @Override
                public void onError(String code, String message) {
                    Tool.showTextToast(context, message);
                }
            });

        } else {
            HttpParams params = new HttpParams();
            params.put("commentId", CommentId);
            HttpUtils.post(Config.MOMENTS_CANCEL_LAUD, params, new HttpCallBack(mActivity) {
                @Override
                public void onSucceed(JSONObject result, String code, String message) {
                    Tool.showTextToast(context, message);
                    mTvPraiseNumber.setText(result.optString("laudNumber"));
                    mIvPraise.setImageResource(R.mipmap.praise_like_up);
                    mTvPraiseNumber.setTextColor(ContextCompat.getColor(context, R.color.black_9));
                    isLikeClick = false;
                    Tool.showTextToast(context, message);
                }

                @Override
                public void onError(String code, String message) {
                    Tool.showTextToast(context, message);
                }
            });
        }
    }

    private void doSendMessage() {
        /**
         *replyMemberId 评论id
         *commentId   回复id
         *comment   评论内容
         * */
        HttpParams params = new HttpParams();
        params.put("replyMemberId", MemberId);
        params.put("commentId", CommentId);
        params.put("comment", mEdInputDialogBox.getText().toString());
        HttpUtils.post(Config.MOMENTS_COMMENT_EDIT, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                /**取消获取焦点  清空数据*/
                mEdInputDialogBox.clearFocus();
                mEdInputDialogBox.setInputType(InputType.TYPE_NULL);
                mEdInputDialogBox.setText("");
                Tool.showTextToast(context, message);
                /**刷新列表数据*/
                onRefresh();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);

            }
        });


    }


    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        // TODO 刷新
        getDetailedData(1, true);
    }


    /**
     * 自动获取editext焦点
     * 弹出键盘
     */
    public void autoPopupKeyboard() {
        mEdInputDialogBox.requestFocus();//获得焦点
        InputMethodManager mInputMethodManager = (InputMethodManager) mEdInputDialogBox.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        mInputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }




    //快捷分享
    private void showShare(boolean silent, String platform){
        final OnekeyShare oks = new OnekeyShare();
//        oks.setNotification(R.drawable.ic_launcher, this.getString(R.string.app_name));

        //不同平台的分享参数，请看文档
//        //http://wiki.mob.com/Android_%E4%B8%8D%E5%90%8C%E5%B9%B3%E5%8F%B0%E5%88%86%E4%BA%AB%E5%86%85%E5%AE%B9%E7%9A%84%E8%AF%A6%E7%BB%86%E8%AF%B4%E6%98%8E
//        String text = "文章分享";
//        oks.setTitle("文章分享");
//        oks.setText(text);
        //oks.setSilent(silent);
        oks.setTitle("文章分享");
        oks.setText(content);
        oks.setTitleUrl(linkUrl);

//        oks.setDialogMode();
        oks.disableSSOWhenAuthorize();
//        File file=new File(Environment.getExternalStorageDirectory() +"/" + Config.base_data_path+"/meixiang.png");
        Log.e("lw","输出当前本地图片="+PostDetailsActivity.TEST_IMAGE);
        if(imagPath==null||imagPath.length()==0){
            Log.e("lw","1");
                oks.setImagePath(PostDetailsActivity.TEST_IMAGE);  //分享sdcard目录下的图片
        }else{
            Log.e("lw","2");
            oks.setImageUrl(imagPath);
        }

        if (platform != null) {
            oks.setPlatform(platform);
        }
        // 去自定义不同平台的字段内容
        // http://wiki.mob.com/Android_%E5%BF%AB%E6%8D%B7%E5%88%86%E4%BA%AB#.E4.B8.BA.E4.B8.8D.E5.90.8C.E5.B9.B3.E5.8F.B0.E5.AE.9A.E4.B9.89.E5.B7.AE.E5.88.AB.E5.8C.96.E5.88.86.E4.BA.AB.E5.86.85.E5.AE.B9
        oks.setShareContentCustomizeCallback(new ShareContentCustomize(content,imagPath,linkUrl));
        oks.show(this);
    }

    private void initImagePath() {
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && Environment.getExternalStorageDirectory().exists()) {
                TEST_IMAGE = Environment.getExternalStorageDirectory().getAbsolutePath() + FILE_NAME;
            } else {
                TEST_IMAGE = getApplication().getFilesDir().getAbsolutePath() + FILE_NAME;
            }
            // 创建图片文件夹
            File file = new File(TEST_IMAGE);
            if (!file.exists()) {
                file.createNewFile();
                Bitmap pic = BitmapFactory.decodeResource(getResources(), R.mipmap.app_logo);
                FileOutputStream fos = new FileOutputStream(file);
                pic.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            }
        } catch (Throwable t) {
            t.printStackTrace();
            TEST_IMAGE = null;

        }


    }





    @Override
    protected void onDestroy() {
        super.onDestroy();
        HttpUtils.tagCancelRequest(TAG);
        ShareSDK.stopSDK();
    }
}

